<!--租客或者未登录状态下的主页-->
<template>
    <el-container class="home-container">
        <HeaderComponent />

        <!-- 主要内容区域 -->
        <div class="main-content" @scroll="handleScroll" ref="containerRef">
            <el-row :gutter="20" class="main-row">
                <!-- 房源列表区域 -->
                <el-col :span="24" class="main-col">
                    <el-card class="house-list">
                        <template #header>
                            <div class="card-header">
                                <span>房源列表</span>
                                <el-select v-model="sortBy" placeholder="排序方式" style="width: 140px"
                                    @change="handleSortChange">
                                    <el-option label="默认排序" value="default"></el-option>
                                    <el-option label="价格从低到高" value="price-asc"></el-option>
                                    <el-option label="价格从高到低" value="price-desc"></el-option>
                                    <el-option label="面积从大到小" value="area-desc"></el-option>
                                </el-select>
                            </div>
                        </template>

                        <!-- 无数据提示 -->
                        <el-empty v-if="houses.length === 0" description="暂无符合条件的房源"></el-empty>

                        <!-- 房源列表 -->
                        <template v-else>
                            <el-row :gutter="20">
                                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" v-for="house in houses"
                                    :key="house.id" class="mb-4">
                                    <el-card :body-style="{ padding: '0px' }" class="house-card" shadow="hover">
                                        <div class="image-container">
                                            <img :src="house.images[0]" class="house-image">
                                            <div class="image-overlay">
                                                <el-button type="primary" size="small"
                                                    @click="viewDetail(house.id)">查看详情</el-button>
                                            </div>
                                        </div>
                                        <div class="house-info">
                                            <h3 class="house-title">{{ house.title }}</h3>
                                            <p class="house-address"><el-icon>
                                                    <Location />
                                                </el-icon> {{ formatAddress(house.address) }}</p>
                                            <div class="house-tags">
                                                <el-tag size="small">{{ house.houseType }}</el-tag>
                                                <el-tag size="small" type="success">{{ house.area }}㎡</el-tag>
                                                <el-tag v-for="(keyword, index) in house.keywords" :key="index"
                                                    size="small" type="info" class="keyword-tag">{{ keyword }}</el-tag>
                                            </div>
                                            <!--
                                            <div class="house-features">
                                                <span><el-icon>
                                                        <Sunset />
                                                    </el-icon> 朝南</span>
                                                <span><el-icon>
                                                        <OfficeBuilding />
                                                    </el-icon> {{ Math.floor(Math.random() * 20) + 1 }}层</span>
                                                <span><el-icon>
                                                        <Van />
                                                    </el-icon> 距地铁{{ Math.floor(Math.random() * 2000) + 200 }}米</span>
                                            </div>-->
                                            <div class="landlord-info">
                                                <el-avatar :size="30"
                                                    :src="house.landlord.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
                                                <span class="landlord-name">{{ house.landlord.username }}</span>
                                            </div>
                                            <div class="price-row">
                                                <span class="price">¥{{ house.price }}/月</span>
                                            </div>
                                        </div>
                                    </el-card>
                                </el-col>
                            </el-row>

                            <!-- 底部加载状态 -->
                            <div v-if="loading" class="bottom-loading">
                                <el-loading></el-loading>
                                <span class="loading-text">加载中...</span>
                            </div>

                            <!-- 无更多数据提示 -->
                            <div v-if="noMore" class="no-more">
                                没有更多数据了
                            </div>
                        </template>
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </el-container>
    <el-backtop :right="100" :bottom="100" target=".main-content" />
    <el-dialog v-model="showDetailDialog" title="房屋详情" width="50%" destroy-on-close>
        <template v-if="currentHouse">
            <!-- 图片/视频轮播 -->
            <el-carousel class="detail-carousel">
                <el-carousel-item v-for="(media, index) in currentHouse.images" :key="index">
                    <!-- 判断是否为视频文件 -->
                    <template v-if="isVideoFile(media)">
                        <video class="carousel-item" controls autoplay loop>
                            <source :src="media" :type="getVideoType(media)">
                            您的浏览器不支持视频播放
                        </video>
                    </template>
                    <!-- 图片文件 -->
                    <img v-else :src="media"  class="carousel-item">
                </el-carousel-item>
            </el-carousel>

            <!-- 两列布局容器 -->
            <div class="detail-grid">
                <!-- 左列：基本信息 -->
                <div class="detail-section">
                    <h2 class="detail-title">{{ currentHouse.title }}</h2>
                    <div class="detail-info">
                        <div class="info-item">
                            <el-icon>
                                <Location />
                            </el-icon>
                            <span>{{ formatAddress(currentHouse.address) }}</span>
                        </div>
                        <div class="info-row">
                            <div class="info-item price-item">
                                <span class="label">月租金</span>
                                <span class="value price">¥{{ currentHouse.price }}/月</span>
                            </div>
                            <div class="info-item price-item">
                                <span class="label">押金</span>
                                <span class="value">¥{{ currentHouse.deposit }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">房型</span>
                                <span class="value">{{ currentHouse.houseType }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">面积</span>
                                <span class="value">{{ currentHouse.area }}㎡</span>
                            </div>
                        </div>
                        <div class="tags-container">
                            <el-tag v-for="(keyword, index) in currentHouse.keywords" :key="index" size="small"
                                class="detail-tag">{{ keyword }}</el-tag>
                        </div>
                    </div>
                </div>

                <!-- 右列：房东信息 -->
                <div class="detail-section">
                    <h3 class="section-title">房东信息</h3>
                    <div class="landlord-detail">
                        <div class="landlord-header">
                            <el-avatar :size="50"
                                :src="currentHouse.landlord.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
                            <div class="landlord-basic">
                                <div class="landlord-name">{{ currentHouse.landlord.username }}</div>
                                <div class="landlord-info-row">
                                    <span>{{ currentHouse.landlord.gender === 1 ? '男' : currentHouse.landlord.gender === 2
                                        ? '女' : '性别未知' }}</span>
                                    <span>{{ currentHouse.landlord.age == null ? '年龄未知' : currentHouse.landlord.age + "岁"
                                        }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="contact-info">
                            <div class="info-item">
                                <el-icon>
                                    <Phone />
                                </el-icon>
                                <span>{{ currentHouse.landlord.phone || '未知' }}</span>
                            </div>
                            <div class="info-item">
                                <el-icon>
                                    <Message />
                                </el-icon>
                                <span>{{ currentHouse.landlord.email || '未知' }}</span>
                            </div>
                        </div>
                        <!--
                    <div class="landlord-description">
                        {{ houseDetail.landlord_description==null?'暂无描述': houseDetail.landlord_description }}
                    </div>-->
                        <el-button type="primary" @click="contactLandlord" :disabled="userRole == 0">联系房东</el-button>
                    </div>
                </div>
            </div>

            <!-- 发布时间 -->
            <div class="publish-time">
                发布时间：{{ currentHouse.create_time }}
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted,watch } from 'vue'
import { Location, Phone, Message } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import HeaderComponent from '@/components/HeaderComponent.vue'
import apiClient from '@/api/api'
import {House}from '@/utils/house'
import formatAddress from '@/utils/house'
// 引入 router 后获取当前路由对象
import { useRoute } from 'vue-router'
import router from '@/router'
// 从store中获取用户登录状态和身份信息
const userRole = ref(0) // 1: 管理员, 2: 租客, 3: 房东

// 房源列表数据
const houses = ref<House[]>([])
// 分页信息
const currentPage = ref(1)
const pageSize = ref(12)
// 排序方式
const sortBy = ref('default')
// 加载状态
const loading = ref(false)
// 是否无更多数据
const noMore = ref(false)
// 容器引用
const containerRef = ref<HTMLElement | null>(null)
// 防抖定时器
const debounceTimer = ref<number | null>(null)
// 房屋详情
const currentHouse = ref<House>()
// 房屋详情弹窗是否可见
const showDetailDialog = ref(false)
// 排序变化处理
const handleSortChange = () => {
    // 重置分页相关数据
    currentPage.value = 1
    houses.value = []
    noMore.value = false
    //如果处于搜索状态，则重新加载搜索结果
    if (searchParams.value.keyword || searchParams.value.region || searchParams.value.houseType || 
        searchParams.value.rentType || searchParams.value.minPrice || searchParams.value.maxPrice) {
        loadSearchHouses()
    }
    // 重新加载数据
    loadHouses()
}
// 新增搜索参数响应
const searchParams = ref({
    keyword: '',
    region: '',
    houseType: '',
    rentType: '',
    minPrice: '',
    maxPrice: ''
})
//处理搜索后的结果渲染
// 监听路由参数变化
const route = useRoute()
watch(() => route.query, (newQuery) => {
    console.log("路由参数变化：", newQuery)
    searchParams.value = {
        keyword: newQuery.keyword as string || '',
        region: newQuery.region as string || '',
        houseType: newQuery.houseType as string || '',
        rentType: newQuery.rentType as string || '',
        minPrice: newQuery.minPrice ? newQuery.minPrice as string : '',
        maxPrice: newQuery.maxPrice? newQuery.maxPrice as string : ''
    }
    currentPage.value = 1
    houses.value = []
    noMore.value = false
    loadSearchHouses()
})

//加载搜索数据
const loadSearchHouses = async () => {
    if (loading.value || noMore.value) return
    loading.value = true
    try {
        const res = await apiClient.get('/house/searchresult', {
            params: {
                page: currentPage.value,
                size: pageSize.value,
                order: sortBy.value === 'default'? 0 : sortBy.value === 'price-desc'? 1 : sortBy.value === 'price-asc'? 2 : 3,
                keyword: searchParams.value.keyword,            
                region: searchParams.value.region,
                houseType: searchParams.value.houseType,
                rentType: searchParams.value.rentType,
                minPrice: searchParams.value.minPrice,
                maxPrice: searchParams.value.maxPrice
            }
        })
        console.log("筛选条件"+ searchParams.value)
        if (res.data.code === 1) {
            houses.value.push(...res.data.data.list)
            console.log("初始化数据"+res.data.data.list)
            if (res.data.data.length < pageSize.value) {
                noMore.value = true
            }
            currentPage.value++
        }
        else {
            ElMessage.error(res.data.message)
        }
    }catch (error) {
        console.error('加载房源数据失败:', error)
        ElMessage.error('加载房源数据失败')
    }
    finally {
        loading.value = false
    }

}






// 加载数据
const loadHouses = async () => {
    if (loading.value || noMore.value) return

    loading.value = true
    try {
        const res = await apiClient.get('/house/getHouseList', {
            params: {
                page: currentPage.value,
                size: pageSize.value,
                order: sortBy.value === 'default' ? 0 : sortBy.value === 'price-desc' ? 1 : sortBy.value === 'price-asc' ? 2 : 3
            }
        })
        if (res.data.code === 1) {
            houses.value.push(...res.data.data.list)
            console.log("初始化数据"+res.data.data.list)
            if (res.data.data.length < pageSize.value) {
                noMore.value = true
            }
            currentPage.value++
        } else {
            ElMessage.error(res.data.message)
        }
    } catch (error) {
        console.error('加载房源数据失败:', error)
        ElMessage.error('加载房源数据失败')
    } finally {
        loading.value = false
    }
}

// 滚动处理
const handleScroll = () => {
    if (!containerRef.value) return

    // 清除之前的定时器
    if (debounceTimer.value) {
        clearTimeout(debounceTimer.value)
    }

    // 设置新的定时器
    debounceTimer.value = window.setTimeout(() => {
        const { scrollTop, clientHeight, scrollHeight } = containerRef.value!
        // 当距离底部还有100px时触发加载
        if (scrollHeight - scrollTop - clientHeight < 100 && !loading.value && !noMore.value) {
            //添加判断条件，如果有搜索数据，则加载搜索数据，否则加载普通数据
            if (searchParams.value.keyword || searchParams.value.region || 
            searchParams.value.houseType || searchParams.value.rentType || 
            searchParams.value.minPrice || searchParams.value.maxPrice) {
                loadSearchHouses()
            }
            loadHouses()
        }
    }, 200) // 200ms的防抖时间
}

// 查看房屋详情
const viewDetail = (id: number) => {
    // 从当前列表中找到对应id的房源
    const house = houses.value.find(h => h.id === id)
    if (house) {
        currentHouse.value = house
        showDetailDialog.value = true
    } else {
        ElMessage.error('获取房屋详情失败')
    }
}
// 联系房东
const contactLandlord = () => {
    if (userRole.value == 0) {
        ElMessage.warning('请先登录')
        return
    }
    console.log(currentHouse.value?.landlord.id)
    if (currentHouse.value) {
        router.push({
            path: '/chat',
            query: {
                targetId: currentHouse.value.landlord.id,
                landlordName: currentHouse.value.landlord.username
            }
        })
    }

}

// 判断是否为视频文件
const isVideoFile = (url: string): boolean => {
    if (!url) return false
    const fileName = url.toLowerCase()
    return fileName.endsWith('.mp4') || fileName.endsWith('.webm') || 
           fileName.endsWith('.avi') || fileName.endsWith('.mov')
}

// 获取视频MIME类型
const getVideoType = (url: string): string => {
    if (!url) return ''
    const fileName = url.toLowerCase()
    if (fileName.endsWith('.mp4')) return 'video/mp4'
    if (fileName.endsWith('.webm')) return 'video/webm'
    if (fileName.endsWith('.avi')) return 'video/x-msvideo'
    if (fileName.endsWith('.mov')) return 'video/quicktime'
    return ''
}
// 组件挂载时加载数据
onMounted(async () => {
    document.title = '房屋租赁系统'
    userRole.value = Number(localStorage.getItem('userRole'))
    // 加载房源数据
    loadHouses()
    if (containerRef.value) {
        containerRef.value.addEventListener('scroll', handleScroll)
    }
})
// 组件卸载时清除事件监听器
onUnmounted(() => {
    if (containerRef.value) {
        containerRef.value.removeEventListener('scroll', handleScroll)
    }
    // 清除定时器
    if (debounceTimer.value) {
        clearTimeout(debounceTimer.value)
    }
})

</script>

<style scoped>
.main-content {
    width: 100%;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    overflow-x: hidden;
    height: calc(100vh - 80px);
    overflow-y: auto;
    padding-top: 60px;
}

.main-row {
    width: 90%;
}

.el-menu-vertical {
    height: calc(100vh - 60px);
    border-right: none;
}

.el-main {
    background-color: #f0f2f5;
    padding: 20px;
}

.house-list {
    border-radius: 8px;
    padding: 0;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.house-card {
    margin-bottom: 20px;
    transition: all 0.3s;
    border-radius: 8px;
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.image-container {
    position: relative;
    overflow: hidden;
}

.house-image {
    width: 100%;
    height: 240px;
    object-fit: cover;
    transition: transform 0.5s;
}

.image-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.5);
    padding: 10px;
    display: flex;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
}

.house-card:hover .image-overlay {
    opacity: 1;
}

.house-card:hover .house-image {
    transform: scale(1.05);
}

.house-info {
    padding: 16px;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
}

.house-title {
    margin: 0 0 8px 0;
    font-size: 18px;
    font-weight: bold;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.house-address {
    color: #606266;
    margin: 0 0 12px 0;
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
}

.house-tags {
    margin: 8px 0;
    display: flex;
    gap: 6px;
}

.house-features {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin: 10px 0;
    color: #606266;
    font-size: 13px;
}

.house-features span {
    display: flex;
    align-items: center;
    gap: 4px;
}

.landlord-info {
    display: flex;
    align-items: center;
    margin: 12px 0;
    gap: 8px;
}

.landlord-name {
    font-size: 14px;
    color: #606266;
    text-align: start;
}

.price-row {
    margin-top: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
}

.price {
    color: #f56c6c;
    font-size: 20px;
    font-weight: bold;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    min-height: 200px;
}

.loading-text {
    margin-top: 10px;
    color: #909399;
    font-size: 14px;
}

.no-more {
    text-align: center;
    color: #909399;
    padding: 20px 0;
}

.mb-4 {
    margin-bottom: 16px;
}

.bottom-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
    margin-top: 20px;
}

.loading-text {
    margin-top: 10px;
    color: #909399;
    font-size: 14px;
}

.no-more {
    text-align: center;
    color: #909399;
    padding: 20px 0;
    margin-top: 20px;
}

/* 房屋详情弹窗样式 */
.detail-carousel {
    border-radius: 8px;
    overflow: hidden;
}

.carousel-item {
    width: 100%;
    height: 100%;
    object-fit: contain;
    background-color: #f5f5f5;
}

.detail-grid {
    display: grid;
    grid-template-columns: 1.2fr 0.8fr;
    gap: 20px;
    margin-bottom: 20px;
}

.detail-section {
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.detail-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #303133;
}

.detail-info {
    margin-bottom: 20px;
}

.info-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin: 20px 0;
}

.info-item {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #606266;
}

.info-item .label {
    color: #909399;
    min-width: 60px;
}

.info-item .value {
    font-weight: 500;
}

.price-item .value {
    color: #f56c6c;
    font-size: 24px;
    font-weight: bold;
}

.tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 16px;
}

.detail-tag {
    margin-right: 8px;
}

.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #303133;
}

.landlord-detail {
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.landlord-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;
}

.landlord-basic {
    flex: 1;
}

.landlord-info-row {
    display: flex;
    gap: 16px;
    color: #606266;
    margin-top: 4px;
}

.contact-info {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin: 16px 0;
    padding: 16px 0;
    border-top: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
}

.landlord-description {
    margin-top: 16px;
    color: #606266;
    line-height: 1.6;
}

.publish-time {
    text-align: right;
    color: #909399;
    font-size: 14px;
    margin-top: 20px;
}
</style>
